package com.itheima.stock.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.itheima.stock.constant.StockConstant;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.CaptchaVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
//import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SysUser getUserByUserName(String userName) {
        return userMapper.getUserByUserName(userName);
    }

    public R<LoginRespVo> login(LoginReqVo vo) {
        //判断参数合法性
        if (vo==null || StringUtils.isBlank(vo.getUsername()) || StringUtils.isBlank(vo.getPassword())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //根据用户名查询用户信息
        SysUser user=this.userMapper.findByUserName(vo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR.getMessage());
        }
        //组装登录成功数据
        LoginRespVo respVo = new LoginRespVo();
        //属性名称与类型必须相同，否则属性值无法copy
        BeanUtils.copyProperties(user,respVo);
        return  R.ok(respVo);

    }

//    @Override
    public R<LoginRespVo> login2(LoginReqVo vo) {
        //判断参数合法性
        if (vo==null || StringUtils.isBlank(vo.getUsername()) || StringUtils.isBlank(vo.getPassword())
                || StringUtils.isBlank(vo.getCode()) || StringUtils.isBlank(vo.getSessionId())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        String rCode = (String) redisTemplate.opsForValue().get(StockConstant.CHECK_CODE + vo.getSessionId());
        if (StringUtils.isBlank(rCode) || !rCode.equals(vo.getCode())){
            return R.error(ResponseCode.CHECK_CODE_ERROR);
        }
        //redisTemplate.delete(StockConstant.CHECK_CODE + vo.getSessionId());
        //根据用户名查询用户信息
        SysUser user=this.userMapper.getUserByUserName(vo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.ACCOUNT_NOT_EXISTS);
        }
        //判断密码是否一致
        if (!passwordEncoder.matches(vo.getPassword(), user.getPassword())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //构建LoginRespVo对象
        LoginRespVo loginRespVo = new LoginRespVo();
        /*loginRespVo.setId(user.getId());
        loginRespVo.setUsername(user.getUsername());*/
        //属性名称与类型必须相同，否则属性值无法copy
        BeanUtils.copyProperties(user,loginRespVo);
        return R.ok(loginRespVo);
    }

    @Override
    public R<CaptchaVo> getCaptchaImage() {
        //参数分别是宽、高、验证码长度、干扰线数量
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(250, 40, 4, 5);
        //设置背景颜色清灰
        captcha.setBackground(Color.lightGray);
        //自定义校验码生成方式
//        captcha.setGenerator(new CodeGenerator() {
//            @Override
//            public String generate() {
//                return RandomStringUtils.randomNumeric(4);
//            }
//            @Override
//            public boolean verify(String code, String userInputCode) {
//                return code.equalsIgnoreCase(userInputCode);
//            }
//        });
        //获取图片中的验证码，默认生成的校验码包含文字和数字，长度为4
        String checkCode = captcha.getCode();
        log.info("生成校验码:{}",checkCode);
        //生成sessionId
        String sessionId = String.valueOf(idWorker.nextId());
        //将sessionId和校验码保存在redis下，并设置缓存中数据存活时间一分钟
        redisTemplate.opsForValue().set(StockConstant.CHECK_CODE +sessionId,checkCode,1, TimeUnit.MINUTES);
        //组装响应数据
        HashMap<String, String> info = new HashMap<>();
        info.put("sessionId",sessionId);
        info.put("imageData",captcha.getImageBase64());//获取base64格式的图片数据
        //设置响应数据格式
        //6.响应前端
        CaptchaVo vo = new CaptchaVo();
        vo.setSessionId(sessionId);
        vo.setImageData(captcha.getImageBase64());
        return R.ok(vo);
    }

//    @Override
//    public R<CaptchaVo> getCaptchaImage() {
//        //1.生成算术的图片对象
//        //算术验证码
//        Captcha captcha = new ArithmeticCaptcha(200,20,2);
//        //2.获取图片文字内容和base64图片信息
//        String validateCode = captcha.text();
//        String base64Img = captcha.toBase64();
//        //3.基于雪花算法生成id
//        String sessionId = String.valueOf(idWorker.nextId());
//        //4.向redis保存验证码信息
//        redisTemplate.opsForValue().set(StockConstant.CHECK_CODE+sessionId,validateCode,60, TimeUnit.SECONDS);
//        //5.组装CaptchaVo对象
//        CaptchaVo vo = new CaptchaVo(base64Img,sessionId);
//        //6.响应前端
//        return R.ok(vo);
//    }

}
